package com.takeaway.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author 后台赖骏
 */
public class CreateSimpleMail {
    static final int VERIFICATION_CODE = 6;
    public static MimeMessage createSimpleMail(Session session,String acceptMail) throws Exception {
        //  获取6为随机验证码
        String[] letters = new String[] {
                "q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
                "A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
                "0","1","2","3","4","5","6","7","8","9"};
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < VERIFICATION_CODE; i++) {
            stringBuilder.append(letters[(int) Math.floor(Math.random() * letters.length)]);
        }


        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress("599194514@qq.com"));

        message.setRecipient(Message.RecipientType.TO, new InternetAddress(acceptMail));

        message.setSubject("外卖平台验证码");

        message.setContent("欢迎您注册外卖平台,验证码为(一分钟有效):"+stringBuilder+"", "text/html;charset=UTF-8");


        return message;
    }
    public static String sentMail(String acceptMail) throws Exception{
        String pwdCode = "jfpwopuzssibbcij";
        Properties prop = new Properties();
        // 开启debug调试，以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.qq.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        // 开启SSL加密，否则会失败
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        // 创建session
        Session session = Session.getInstance(prop);
        // 通过session得到transport对象
        Transport ts = session.getTransport();
        // 连接邮件服务器：邮箱类型，帐号，POP3/SMTP协议授权码
        ts.connect("smtp.qq.com", "599194514", pwdCode);
        // 创建邮件
        Message message = CreateSimpleMail.createSimpleMail(session,acceptMail);
        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        String verification = (String) message.getContent();
        ts.close();
        return verification.substring(verification.length() - 6);
    }
}

